/**
 * 受保护的路由组件
 * 用于保护需要认证的路由
 */

import { Navigate, useLocation } from 'react-router-dom'
import { useAuthStore } from '@/store/authStore'
import type { ReactElement } from 'react'

interface ProtectedRouteProps {
  children: ReactElement
}

export default function ProtectedRoute({ children }: ProtectedRouteProps) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)
  const location = useLocation()

  console.log('[ProtectedRoute] isAuthenticated:', isAuthenticated)

  if (!isAuthenticated) {
    console.log('[ProtectedRoute] Redirecting to /login')
    // 未登录，重定向到登录页，并保存当前路径
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  console.log('[ProtectedRoute] Rendering protected content')
  return children
}
